package com.hxgz.steel.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hxgz.steel.config.WeChatConfig;
import org.springframework.beans.factory.annotation.Autowired;

public class WeixinCommenUtil {

  private static final int BLACK = 0xFF000000;
  private static final int WHITE = 0xFFFFFFFF;

  protected static final Logger log = LoggerFactory.getLogger(WeixinCommenUtil.class);

  public static String getOpenId(HttpServletRequest request, HttpServletResponse response,
      String code) {
    String content = "";
    String openId = "";
    String unionId = "";
    //封装获取openId的微信API
    StringBuffer url = new StringBuffer();
    WeChatConfig weChatConfig = new WeChatConfig();
    url.append("https://api.weixin.qq.com/sns/jscode2session?appid=")
        .append(PropertiesUtil.getProperty1("wxopen.appid"))
        .append("&secret=")
        .append(PropertiesUtil.getProperty1("wxopen.appsecret"))
        .append("&js_code=")
        .append(code)
        .append("&grant_type=authorization_code");
    ObjectMapper objectMapper = new ObjectMapper();
    try {
      content = HttpClinet.sendGet(url.toString());
      Map map = objectMapper.readValue(content, Map.class);
      openId = String.valueOf(map.get("openid"));
      log.info("获取的openID：" + openId);
    } catch (JsonParseException e) {
      log.error("json解析失败：", e);
    } catch (JsonMappingException e) {
      log.error("map转换成json失败：", e);
    } catch (Exception e) {
      log.error("http获取openId请求失败：", e);
    }
    return openId;
  }
}